import axios from 'axios';
import { session, STORAGE_KEY } from '@/service/storage.service';


// axios 请求方式枚举
enum METHOD {
  GET = 'GET',
  DELETE = 'DELETE',
  HEAD = 'HEAD',
  OPTIONS = 'OPTIONS',
  POST = 'POST',
  PUT = 'PUT',
  PATCH = 'PATCH',
  PURGE = 'PURGE',
  LINK = 'LINK',
  UNLINK = 'UNLINK',
}
export { METHOD };

/**
 * 构建axios实例并增加拦截器
 * @author WangLiZhi
 * @param baseURL
 * @param config
 * @returns AxiosInstance
 */
function create(baseURL = '', config = {}) {
  // 初始化axios实例
  const http = axios.create({
    timeout: 30000,                                          // 设置超时
    baseURL: baseURL,       // 设置统一接口地址
    headers: {
      'Content-Type': 'application/json;charset=UTF-8;',    // 设置内容数据格式和编码
    },
    ...config
  });

  /**
   * 请求拦截器
   * 1.添加token到header上
   * 2.请求参数数据格式化
   */
  http.interceptors.request.use(
    config => {
      // http header上添加token
      // const token = session.get(STORAGE_KEY.TOKEN);
      // token && (config.headers.Authorization = token)
      return config;
    },
    error => Promise.reject(error)
  );

  // 响应拦截白名单
  const whiteList = [200, 201];
  /**
   * 响应拦截器
   * 1.响应数据格式化
   * 2.请求错误处理
   */
  http.interceptors.response.use(
    response => {
      
      return response;
    },
    error => {
      const status = error?.response?.status
      if (status) {
        let message;
        switch (status) {
          case 400:
            message = '请求错误!';
            break;
          case 401:
            message = '请求错误!';
            break;
          case 404:
            message = '此刻无数据!';
            break;
          case 408:
            message = '请求超时!';
            break;
          case 500:
            message = '服务器内部错误!';
            break;
          case 501:
            message = '服务未实现!';
            break;
          case 502:
            message = '网关错误!';
            break;
          case 503:
            message = '服务不可用!';
            break;
          case 504:
            message = '网关超时!';
            break;
          case 505:
            message = 'HTTP版本不受支持!';
            break;
          default:
            message = '请求失败!'
        }
      }
      return Promise.reject(error);
    }
  );
  return http;
}


// 创建请求接口的axios实例
export const request = create(import.meta.env.VITE_API_URL as string);
// 创建json静态资源的axios实例
export const staticRequest = create(import.meta.env.VITE_PRODUCT_URL as string);

